import threading
import time
from dataclasses import dataclass

from nacos import NacosClient


# nacos配置类
@dataclass
class NacosProperties:
    enable: bool
    addr: str
    username: str
    password: str
    namespace: str
    group: str


# Nacos服务
class NacosService:
    # 初始化
    def __init__(self, properties: NacosProperties):
        """
        初始化配置
        :param properties:
        """
        self.properties = properties
        if properties.enable:
            self.client = NacosClient(server_addresses=properties.addr, namespace=properties.namespace,
                                      username=properties.username, password=properties.password)
        else:
            self.client = None

    def register(self, service_name: str, service_ip: str, service_port: int):
        """
        注册
        :param service_name:
        :param service_ip:
        :param service_port:
        :return:
        """

        def send_heartbeat():
            # 心跳
            while True:
                self.client.send_heartbeat(service_name, service_ip, service_port, group_name=self.properties.group,
                                           ephemeral=True)
                time.sleep(3)

        if self.client:
            self.client.add_naming_instance(service_name, service_ip, service_port, group_name=self.properties.group,
                                            ephemeral=True)
            t = threading.Thread(target=send_heartbeat, daemon=True)
            t.start()

    def deregister(self, service_name: str, service_ip: str, service_port: int):
        """
        取消注册
        :param service_name:
        :param service_ip:
        :param service_port:
        :return:
        """
        self.client.remove_naming_instance(service_name, service_ip, service_port, group_name=self.properties.group,
                                           ephemeral=True)
